import {createRouter, createWebHistory} from 'vue-router'
import * as authUtil from "@/ts/AuthUtils"

/**
 * 手动配置路由
 */
let routes = [
  {
    path:"/",
    redirect: '/userHome',
  }
  ,{
    path:"/login",
    component:()=>import("../views/login.vue")
  },{
    path:"/homeIndex",
    component:()=>import("../web/home/view/index.vue")
  },{
    path: "/homeDocument",
    component:()=>import("../web/home/view/document.vue")
  },{
    path: "/homeTest",
    component:()=>import("../web/home/view/test.vue")
  }
];

/**
 * 自动配置路由，扫描每个包含page.js文件的目录
 */
const pages = import.meta.glob("../views/**/page.js",{
  eager:true,
  import:"default"
})
const comps = import.meta.glob("../views/**/index.vue");

const autoRoutes = Object.entries(pages).map(([path,page])=>{
  const compPath = path.replace("page.js","index.vue");
  path = path.replace("../views","").replace("/page.js","") || "/";
  const name = path.split("/").filter(Boolean).join("-") || "index";
  return{
    path:path,
    name:name,
    page,
    component: comps[compPath]
  }
})

let parentRouter = {
  path:"/templatePage",
  name:"templatePage",
  component:()=>import("../views/PageTemplate.vue"),
  children:autoRoutes
}

routes = routes.concat(parentRouter);

const router = createRouter({
  history:createWebHistory(),
  routes:routes
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/' || to.path === '/login'|| to.path.startsWith("/home") || authUtil.isLogin()) {
    next() // 直接放行登录页
  } else {
      next('/login');
  }
})

export default router
